package com.example.partyfee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.partyfee.config.ExcelConfig;
import com.example.partyfee.dto.SalaryDTO;
import com.example.partyfee.dto.SalaryExcelDTO;
import com.example.partyfee.dto.SalaryQueryDTO;
import com.example.partyfee.entity.Salary;
import com.example.partyfee.excel.SalaryImportListener;
import com.example.partyfee.exception.BusinessException;
import com.example.partyfee.repository.SalaryRepository;
import com.example.partyfee.service.SalaryService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 工资服务实现类
 */
@Service
@RequiredArgsConstructor
public class SalaryServiceImpl extends ServiceImpl<SalaryRepository, Salary> implements SalaryService {

    private final SalaryRepository salaryRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createSalary(SalaryDTO salaryDTO) {
        // 检查身份证号和标识号是否已存在于同一月份
        if (salaryRepository.selectCount(new LambdaQueryWrapper<Salary>()
                .eq(Salary::getIdCard, salaryDTO.getIdCard())
                .eq(Salary::getSalaryMonth, salaryDTO.getSalaryMonth())) > 0) {
            throw new BusinessException("该月份已存在此身份证号的工资数据");
        }

        if (salaryRepository.selectCount(new LambdaQueryWrapper<Salary>()
                .eq(Salary::getIdentifier, salaryDTO.getIdentifier())
                .eq(Salary::getSalaryMonth, salaryDTO.getSalaryMonth())) > 0) {
            throw new BusinessException("该月份已存在此标识号的工资数据");
        }

        Salary salary = new Salary();
        BeanUtils.copyProperties(salaryDTO, salary);
        salary.setCreateTime(LocalDateTime.now());
        salary.setBatchNo(UUID.randomUUID().toString());
        salaryRepository.insert(salary);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSalary(Long id, SalaryDTO salaryDTO) {
        Salary salary = salaryRepository.selectById(id);
        if (salary == null) {
            throw new BusinessException("工资数据不存在");
        }

        // 检查身份证号和标识号是否已存在于同一月份（排除自身）
        if (!salary.getIdCard().equals(salaryDTO.getIdCard()) &&
                salaryRepository.selectCount(new LambdaQueryWrapper<Salary>()
                        .eq(Salary::getIdCard, salaryDTO.getIdCard())
                        .eq(Salary::getSalaryMonth, salaryDTO.getSalaryMonth())) > 0) {
            throw new BusinessException("该月份已存在此身份证号的工资数据");
        }

        if (!salary.getIdentifier().equals(salaryDTO.getIdentifier()) &&
                salaryRepository.selectCount(new LambdaQueryWrapper<Salary>()
                        .eq(Salary::getIdentifier, salaryDTO.getIdentifier())
                        .eq(Salary::getSalaryMonth, salaryDTO.getSalaryMonth())) > 0) {
            throw new BusinessException("该月份已存在此标识号的工资数据");
        }

        BeanUtils.copyProperties(salaryDTO, salary);
        salaryRepository.updateById(salary);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSalary(Long id) {
        if (salaryRepository.deleteById(id) == 0) {
            throw new BusinessException("工资数据不存在");
        }
    }

    @Override
    public Salary getSalary(Long id) {
        Salary salary = salaryRepository.selectById(id);
        if (salary == null) {
            throw new BusinessException("工资数据不存在");
        }
        return salary;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> importSalariesFromExcel(MultipartFile file, String salaryMonth) throws IOException {
        String batchNo = UUID.randomUUID().toString();
        SalaryImportListener listener = new SalaryImportListener(this, salaryMonth, batchNo);
        ExcelConfig.getReadBuilder(file.getInputStream(), SalaryExcelDTO.class)
                .registerReadListener(listener)
                .sheet()
                .doRead();
        return listener.getErrorMessages();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveSalaries(List<Salary> salaries) {
        if (salaries == null || salaries.isEmpty()) {
            return;
        }
        this.saveBatch(salaries);
    }

    @Override
    public IPage<Salary> getSalaryPage(SalaryQueryDTO queryDTO) {
        LambdaQueryWrapper<Salary> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
            wrapper.and(w -> w
                    .like(Salary::getName, queryDTO.getKeyword())
                    .or()
                    .like(Salary::getIdCard, queryDTO.getKeyword())
                    .or()
                    .like(Salary::getIdentifier, queryDTO.getKeyword())
            );
        }
        
        // 班级筛选
        if (StringUtils.isNotBlank(queryDTO.getClassName())) {
            wrapper.eq(Salary::getClassName, queryDTO.getClassName());
        }
        
        // 职务筛选
        if (StringUtils.isNotBlank(queryDTO.getPosition())) {
            wrapper.eq(Salary::getPosition, queryDTO.getPosition());
        }
        
        // 月份筛选
        if (StringUtils.isNotBlank(queryDTO.getSalaryMonth())) {
            wrapper.eq(Salary::getSalaryMonth, queryDTO.getSalaryMonth());
        }
        
        // 排序
        wrapper.orderByDesc(Salary::getCreateTime);
        
        return salaryRepository.selectPage(
                new Page<>(queryDTO.getCurrent(), queryDTO.getSize()),
                wrapper
        );
    }

    @Override
    public List<String> getSalaryMonths() {
        return salaryRepository.findAllMonths();
    }

    @Override
    public void exportSalariesToExcel(SalaryQueryDTO queryDTO, HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("工资信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询数据
        queryDTO.setSize(Integer.MAX_VALUE);
        queryDTO.setCurrent(1);
        IPage<Salary> page = this.getSalaryPage(queryDTO);
        List<SalaryExcelDTO> excelData = page.getRecords().stream()
                .map(salary -> {
                    SalaryExcelDTO dto = new SalaryExcelDTO();
                    dto.setClassName(salary.getClassName());
                    dto.setPosition(salary.getPosition());
                    dto.setName(salary.getName());
                    dto.setIdCard(salary.getIdCard());
                    dto.setIdentifier(salary.getIdentifier());
                    dto.setBasicSalary(salary.getBasicSalary());
                    dto.setPerformanceSalary(salary.getPerformanceSalary());
                    dto.setIndividualBonus(salary.getIndividualBonus());
                    dto.setEnterprisePension(salary.getEnterprisePension());
                    dto.setEndowmentInsurance(salary.getEndowmentInsurance());
                    dto.setUnemploymentInsurance(salary.getUnemploymentInsurance());
                    dto.setMedicalInsurance(salary.getMedicalInsurance());
                    dto.setHousingFund(salary.getHousingFund());
                    dto.setPersonalTax(salary.getPersonalTax());
                    dto.setDeductionOne(salary.getDeductionOne());
                    dto.setDeductionTwo(salary.getDeductionTwo());
                    return dto;
                })
                .collect(Collectors.toList());

        // 导出Excel
        ExcelConfig.getWriteBuilder(response.getOutputStream(), SalaryExcelDTO.class)
                .sheet("工资信息")
                .doWrite(excelData);
    }
} 